<script setup lang="ts">
import router from '@/router'
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import myAvatar from '@/assets/avatar.png'

/**
 * 用户数据
 */
const userStore = useUserStore()

/**
 * 菜单栏路由状态
 */
let activeIndex = ref('home')
const handleRoute = (index: string) => {
  activeIndex.value = index
}
//路由监听：防止切换页面后，菜单栏路由状态丢失
let route = useRoute()
watch(
  () => route.path,
  (newVal) => {
    activeIndex.value = newVal.split('/')[1]
  },
  { immediate: true }
)

/**
 * 头像事件
 */
const handleDropdown = (command: string) => {
  if (command === 'a') {
    userStore.logout()
    router.push('/login')
  }
}
</script>

<template>
  <div class="app-header">
    <el-row>
      <el-col :span="5">
        <router-link to="/home" class="logo-title flex">
          <img src="@/assets/logo.png" style="width: 30px" />
          <span style="margin-left: 10px">多西柚红白机</span>
        </router-link>
      </el-col>
      <el-col :span="17">
        <el-menu
          :router="true"
          :active-index="activeIndex"
          :default-active="activeIndex"
          class="el-menu"
          mode="horizontal"
          @select="handleRoute"
          style="border-style: none"
        >
          <el-menu-item index="home">首页</el-menu-item>
          <el-menu-item index="gamelist">游戏列表</el-menu-item>
        </el-menu>
      </el-col>
      <el-col :span="2">
        <el-dropdown v-if="userStore.user.isLogin" @command="handleDropdown">
          <el-avatar :src="myAvatar" class="el-dropdown-link" />

          <template #dropdown>
            <h3 v-if="userStore.user.nickname" style="text-align: center">
              {{ userStore.user.nickname }}
            </h3>
            <el-dropdown-menu>
              <el-dropdown-item command="a">
                <el-icon><user /></el-icon>
                退出登录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <router-link v-else to="/login">
          <el-avatar>登录</el-avatar>
        </router-link>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.el-row .el-col:nth-child(odd) {
  display: flex;
  align-items: center;
  justify-content: center;
}
.logo-title {
  font-size: 20px;
  font-weight: bold;
  color: #00b1dd;
  text-decoration: none;
}

.el-dropdown-link:focus {
  outline: none;
}
</style>
